<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/greenwood.gitee.io/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/greenwood.gitee.io/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/greenwood.gitee.io/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/greenwood.gitee.io/images/logo.svg" color="#222">

<link rel="stylesheet" href="/greenwood.gitee.io/css/main.css">


<link rel="stylesheet" href="/greenwood.gitee.io/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/greenwood.gitee.io/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="题目描述原题连接">
<meta property="og:type" content="article">
<meta property="og:title" content="字典树 Leetcode 211 添加与搜索单词 - 数据结构设计">
<meta property="og:url" content="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/10/19/%E5%AD%97%E5%85%B8%E6%A0%91/index.html">
<meta property="og:site_name" content="我看刑">
<meta property="og:description" content="题目描述原题连接">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/10/19/%E5%AD%97%E5%85%B8%E6%A0%91/image-20211019084358693.png">
<meta property="og:image" content="https://pic.leetcode-cn.com/1618365912-EDUCmo-208.003.jpeg#id=sR76J&amp;originHeight=1080&amp;originWidth=1920&amp;originalType=binary&amp;ratio=1&amp;status=done&amp;style=none">
<meta property="article:published_time" content="2021-10-19T00:29:54.000Z">
<meta property="article:modified_time" content="2021-10-19T01:06:39.679Z">
<meta property="article:author" content="Dybala">
<meta property="article:tag" content="算法">
<meta property="article:tag" content="字典树">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/10/19/%E5%AD%97%E5%85%B8%E6%A0%91/image-20211019084358693.png">

<link rel="canonical" href="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/10/19/%E5%AD%97%E5%85%B8%E6%A0%91/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>字典树 Leetcode 211 添加与搜索单词 - 数据结构设计 | 我看刑</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/greenwood.gitee.io/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">我看刑</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/greenwood.gitee.io/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/greenwood.gitee.io/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/greenwood.gitee.io/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/greenwood.gitee.io/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-commonweal">

    <a href="/greenwood.gitee.io/404/" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/10/19/%E5%AD%97%E5%85%B8%E6%A0%91/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/greenwood.gitee.io/images/avatar.gif">
      <meta itemprop="name" content="Dybala">
      <meta itemprop="description" content="日子越来越有判头了">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我看刑">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          字典树 Leetcode 211 添加与搜索单词 - 数据结构设计
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-10-19 08:29:54 / 修改时间：09:06:39" itemprop="dateCreated datePublished" datetime="2021-10-19T08:29:54+08:00">2021-10-19</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/greenwood.gitee.io/categories/Leetcode/" itemprop="url" rel="index"><span itemprop="name">Leetcode</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="题目描述"><a href="#题目描述" class="headerlink" title="题目描述"></a>题目描述</h1><p><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/design-add-and-search-words-data-structure/">原题连接</a></p>
<p><img src="image-20211019084358693.png" alt="image-20211019084358693"></p>
<span id="more"></span>
<h1 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h1><p>匹配字符串数组，用到了一个新技术——字典树</p>
<h2 id="字典树"><a href="#字典树" class="headerlink" title="字典树"></a>字典树</h2><p>顾名思义，将单词映射到一颗树上，每次查找树上是否有符合要求的节点。<br>关于单个节点，这是一颗26叉树，对应26个字母；其次，单个节点还应包括一个flag，标识该节点是不是一个单词的结束。<br>由于是树结构，因此不存在回路，也就是说只要单词不一样，则路径一定不一样<br>单个节点的定义<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">node</span></span>&#123;</span><br><span class="line">       node []next=<span class="keyword">new</span> node[<span class="number">26</span>];</span><br><span class="line">       <span class="keyword">boolean</span> isEnd=<span class="keyword">false</span>;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure><br><img src="https://pic.leetcode-cn.com/1618365912-EDUCmo-208.003.jpeg#id=sR76J&amp;originHeight=1080&amp;originWidth=1920&amp;originalType=binary&amp;ratio=1&amp;status=done&amp;style=none" alt="img"></p>
<h2 id="插入流程"><a href="#插入流程" class="headerlink" title="插入流程"></a>插入流程</h2><p>首先遍历word字符串，对于第i个字符，查看第i层的相应节点的next数组中i+1是否为空，若是，则新建，否则则忽略，然后跳入到i+1节点。当一个单词遍历到最后时，向最后一个节点修改标志变量，标识一个单词的结尾。</p>
<h1 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">WordDictionary</span> </span>&#123;</span><br><span class="line">    node root;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">WordDictionary</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        root = <span class="keyword">new</span> node();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addWord</span><span class="params">(String word)</span> </span>&#123;</span><br><span class="line">        node car = root;</span><br><span class="line">        <span class="keyword">char</span> []str=word.toCharArray();</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">char</span> c:str)&#123;</span><br><span class="line">            <span class="keyword">int</span> value=c-<span class="string">&#x27;a&#x27;</span>;</span><br><span class="line">            <span class="keyword">if</span>(car.next[value]==<span class="keyword">null</span>)&#123;</span><br><span class="line">                car.next[value]=<span class="keyword">new</span> node();</span><br><span class="line">            &#125;</span><br><span class="line">            car=car.next[value];</span><br><span class="line">        &#125;</span><br><span class="line">        car.isEnd=<span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">search</span><span class="params">(String word)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> find(word,<span class="number">0</span>,root);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">find</span><span class="params">(String word,<span class="keyword">int</span> start,node root)</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(start&gt;=word.length())<span class="keyword">return</span> root.isEnd;</span><br><span class="line">        <span class="keyword">char</span> c=word.charAt(start);</span><br><span class="line">        <span class="keyword">if</span>(c!=<span class="string">&#x27;.&#x27;</span>)&#123;</span><br><span class="line">            <span class="keyword">if</span>(root.next[c-<span class="string">&#x27;a&#x27;</span>]==<span class="keyword">null</span>)<span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            <span class="keyword">return</span> find(word,start+<span class="number">1</span>,root.next[c-<span class="string">&#x27;a&#x27;</span>]);</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="keyword">boolean</span> flag=<span class="keyword">false</span>;</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;<span class="number">26</span>;i++)&#123;</span><br><span class="line">                <span class="keyword">if</span>(root.next[i]!=<span class="keyword">null</span>)</span><br><span class="line">                flag=flag|find(word,start+<span class="number">1</span>,root.next[i]);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> flag;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// return false;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">node</span></span>&#123;</span><br><span class="line">        node []next=<span class="keyword">new</span> node[<span class="number">26</span>];</span><br><span class="line">        <span class="keyword">boolean</span> isEnd=<span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Your WordDictionary object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"> * WordDictionary obj = new WordDictionary();</span></span><br><span class="line"><span class="comment"> * obj.addWord(word);</span></span><br><span class="line"><span class="comment"> * boolean param_2 = obj.search(word);</span></span><br><span class="line"><span class="comment"> */</span>                                            </span><br></pre></td></tr></table></figure>
    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/greenwood.gitee.io/tags/%E7%AE%97%E6%B3%95/" rel="tag"># 算法</a>
              <a href="/greenwood.gitee.io/tags/%E5%AD%97%E5%85%B8%E6%A0%91/" rel="tag"># 字典树</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/greenwood.gitee.io/2021/10/18/2035/" rel="prev" title="Leetcode2035 将数组分成两个数组并最小化数组和的差">
      <i class="fa fa-chevron-left"></i> Leetcode2035 将数组分成两个数组并最小化数组和的差
    </a></div>
      <div class="post-nav-item">
    <a href="/greenwood.gitee.io/2021/10/19/leetcode940/" rel="next" title="leetcode940">
      leetcode940 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%A2%98%E7%9B%AE%E6%8F%8F%E8%BF%B0"><span class="nav-number">1.</span> <span class="nav-text">题目描述</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%88%86%E6%9E%90"><span class="nav-number">2.</span> <span class="nav-text">分析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AD%97%E5%85%B8%E6%A0%91"><span class="nav-number">2.1.</span> <span class="nav-text">字典树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8F%92%E5%85%A5%E6%B5%81%E7%A8%8B"><span class="nav-number">2.2.</span> <span class="nav-text">插入流程</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0"><span class="nav-number">3.</span> <span class="nav-text">代码实现</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Dybala</p>
  <div class="site-description" itemprop="description">日子越来越有判头了</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/greenwood.gitee.io/archives/">
        
          <span class="site-state-item-count">22</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/greenwood.gitee.io/categories/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/greenwood.gitee.io/tags/">
          
        <span class="site-state-item-count">22</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Dybala</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/greenwood.gitee.io/lib/anime.min.js"></script>
  <script src="/greenwood.gitee.io/lib/velocity/velocity.min.js"></script>
  <script src="/greenwood.gitee.io/lib/velocity/velocity.ui.min.js"></script>

<script src="/greenwood.gitee.io/js/utils.js"></script>

<script src="/greenwood.gitee.io/js/motion.js"></script>


<script src="/greenwood.gitee.io/js/schemes/pisces.js"></script>


<script src="/greenwood.gitee.io/js/next-boot.js"></script>




  















  

  

  

</body>
</html>
